using Dapper;
using Finance.Api.Read.Applications.Commands.库存盘点;
using Finance.Api.Read.Dtos;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Text;
using System.Linq;

namespace Finance.Api.Read.Applications.CommandHands.库存盘点
{
    /// <summary>
    /// 入库记录查询处理器
    /// </summary>
    public class InRecordQueryCommandHandlers : IRequestHandler<InRecordQueryCommand, ApiResult<List<InRecordDto>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<InRecordQueryCommandHandlers> _logger;

        public InRecordQueryCommandHandlers(IDapperDb db, ILogger<InRecordQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<List<InRecordDto>>> Handle(InRecordQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<InRecordDto>>();
            StringBuilder stringBuilder = new StringBuilder();

            var parameters = new DynamicParameters();
            try
            {
                // 两表联查：入库信息表、入库详情表
                stringBuilder.Append(@"SELECT 
                            gb.InNo,
                            gb.InTime,
                            gb.InType,
                            gb.BoxName,
                            gd.ProductNo,
                            gd.ProductName,
                            gb.Message
                    FROM GoinBox gb
                    INNER JOIN GoinDetail gd ON gb.Id = gd.Goinid
                    WHERE 1=1
                            AND gb.IsDelete = 0 
                            AND gd.IsDelete = 0
                            AND gd.checkid = @checkid");

                // 添加盘点表主键ID参数
                parameters.Add("checkid", request.checkid);

                // 添加排序
                stringBuilder.Append(" ORDER BY gb.InTime DESC, gb.InNo");

                // 记录SQL语句用于调试
                var sql = stringBuilder.ToString();
                _logger.LogInformation("入库记录查询SQL: {SQL}, checkid: {CheckId}", sql, request.checkid);

                // 执行数据查询
                var list = await _db.Query<InRecordDto>(sql, parameters);
                
                result.data = list.ToList();
                result.message = $"入库记录查询成功，找到 {result.data.Count} 条记录";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("入库记录查询失败: {Message}", ex.Message);
                result.message = "入库记录查询失败";
                result.Code = Enumcode.fail;
                throw;
            }

            return await Task.FromResult(result);
        }
    }
} 